const express = require ('express');
const router = express.Router ();
const db = require ('../../db'); // 引入数据库封装模块
const $sql = require ('../../sqlMap');
const bcrypt = require ('bcryptjs');
const jwt = require ('jwt-simple');
const moment = require ('moment');
/* GET 获取用户列表 page. */
// 查询users表
router
  .get ('/user/userList', function (req, res, next) {
    let sql = $sql.user.SELECT_S;
    db.query (sql, function (err, result) {
      if (result) {
        for (item in result) {
          result[item].create_time=moment(result[item].create_time).format("YYYY-MM-DD HH:mm:ss")
        }
        return db.jsonWrite (res, {data: result });
      }
    });
  })
  /**
     * 新增用户
     */
  .post ('/user/addUser', (req, res) => {
    let sql = $sql.user.ADD_I;
    let params = req.body;
    let require = db.hasAllRequired (params, ['username', 'password']);
    db.query ($sql.user.USERINFO_S, [params.username], function (
      result,
      fields
    ) {
      if (result.length > 0) {
        db.jsonWrite (res, {code: 10001, data: {}, msg: '该用户已经存在'});
      } else {
        if (require.require) {
          let salt = bcrypt.genSaltSync (10);
          /* 生成HASH值 */
          var endPaw = bcrypt.hashSync (params.password, salt);
          db.query (sql, [params.username, endPaw], function (result, fields) {
            if (result) {
              db.jsonWrite (res, {data: result});
            }
          });
        } else {
          db.jsonWrite (res, {code: 10001, data: {}, msg: require.msg});
        }
      }
    });
  })
  /**
     * 登录接口
     */
  .post ('/login', (req, res) => {
    let param = req.body;
    let require = db.hasAllRequired (param, ['username', 'password']);
    if (require.require) {
      db.query ($sql.user.USERINFO_S, [param.username], function (
        result,
        fields
      ) {
        if (result.length > 0) {
          if (!bcrypt.compareSync (param.password, result[0].password)) {
            res.json ({code: 10001, data: {}, msg: '用户密码错误'});
          } else {
            let expires = moment ().add (1, 'day').valueOf (); // 设置过期时间
            console.log ('expires', expires);
            let token = jwt.encode (
              {
                iss: param.username,
                exp: expires,
              },
              'jstSecret'
            );
            req.session.token = token;
            result[0].access_token = token;
            res.json ({code: 0, data: result[0], msg: '请求成功'});
          }
        } else {
          res.json ({code: 10001, data: {}, msg: '用户名不存在'});
        }
      });
    } else {
      res.json ({code: 10001, data: {}, msg: require.msg});
    }
  })
  /**
	* 删除用户
 */
  .post ('/user/delUser', (req, res) => {
    let param=req.body
    let require = db.hasAllRequired (req.body, ['id']);
    if (require.require) {
      db.query ($sql.user.USER_D, [param.id], (result, fields) => {
        console.log('jinlai',result)
        if (result.affectedRows > 0) {
					res.json ({code: 0, data: {}, msg: '删除用户成功！'});
        }else{
          res.json ({code: 1, data: {}, msg: '用户不存在！'});
        }
      });
    }
  });
module.exports = router;
